define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/order/index',
                    edit_url: 'order/order/edit',
                    del_url: 'order/order/del',
                    table: 'order',
                }
            });

            var table = $("#table");

            // 修改弹窗大小
            Table.button.edit.extend = 'data-toggle="tooltip" data-area=\'["100%", "100%"]\'';

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'order.id',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), sortable: true },
                        { field: 'code', title: __('code'), operate: 'LIKE' },
                        {
                            field: 'business.nickname_text', title: __('busid'), operate: 'LIKE',
                            
                        },
                        // { field: 'businessaddrid', title: __('businessaddrid'), operate: 'LIKE'},
                        { field: 'amount', title: __('amount'), operate: 'LIKE' },
                        // { field: 'status', title: __('status'), searchable: false },
                        { field: 'status', title: __('Status'), searchList: { "0": __('未支付'), "1": __('已支付'), "2": __('已发货'), "3": __('已收货'), "-1": __('退货') }, formatter: Table.api.formatter.status },
                        // { field: 'status_text', title: __('status'), searchList: { "0": __('未支付'), "1": __('已支付'), "2": __('已发货'), "3": __('已收货'), "-1": __('退货') }, formatter: Table.api.formatter.status },
                        { field: 'createtime', title: __('createtime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange'},
                        { field: 'checkmanid', title: __('checkmanid'), searchable: false },
                        { field: 'admin.username', title: __('shipmanid'), searchable: false },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons:[
                                {
                                    name: 'send',
                                    title: '确认发货',
                                    classname: 'btn btn-xs btn-success btn-ajax',
                                    icon: 'fa fa-leaf',
                                    confirm: '确认发货吗？',
                                    url: 'order/order/send',
                                    success: function (data, ret) {
                                        $(".btn-refresh").trigger("click");
                                    },
                                    error: function (err) {
                                        console.log(err);
                                    },
                                    visible: function (row) {
                                        // console.log(row);
                                        return row.status == 1 ? true : false
                                    }
                                },
                                {
                                    name: 'detail',
                                    title: '详情',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'order/order/info',
                                    icon: 'fa fa-eye',
                                    extend: 'data-toggle=\'tooltip\' data-area= \'["100%", "100%"]\'', //重点是这一句
                                },
                                {
                                    name: 'cancel',
                                    title: '撤销发货',
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    icon: 'fa fa-reply',
                                    url: 'order/order/cancel',
                                    confirm: '确认要撤回发货吗？',
                                    success: function (data, ret) {
                                        $(".btn-refresh").trigger("click");
                                    },
                                    error: function (err) {
                                        console.log(err);
                                    },
                                    visible: function (row) {
                                        if (row.status == 2) {
                                            return true
                                        }
                                        return false
                                    }
                                },
                                // fa fa-paper-plane
                                {
                                    name: 'express',
                                    title: '查看物流',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: 'order/order/express',
                                    icon: 'fa fa-paper-plane',
                                    // extend: 'data-toggle=\'tooltip\' data-area= \'["100%", "100%"]\'', //重点是这一句
                                    visible: function (row) {
                                        // console.log(row);
                                        if (row.status == 2 ) {
                                            return true
                                        }else if(row.status ==3){
                                            return true
                                        }
                                        return false
                                    }
                                },
                            ]
                        }
                    ]
                ],
                escape:false,
                // search:false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            // 获取客户
            var business=Config.Product.business;
            // console.log(business);

            // 更改收货地址
            $('#addresstext').click(function (){
                console.log(business.id);
                // console.log(business.nickname_text);
                Backend.api.open("order/order/address?busid="+business.id, '客户'+business.nickname+"的收货地址", {
                    area: ['80%', '80%'],
                    callback: function (data) {
                        console.log(data);
                        $('#addresstext').val(data.address_text)
                        $('#businessaddrid').val(data.id)

                        $('#c-address').val(data.address)
                    }
                })
            })
            
            // 初始化表格
            $('#table').bootstrapTable({
                columns: [
                    {
                        field: 'id',
                        title: __('Id')
                    },
                    {
                        field: 'name',
                        title: __('Name'),
                    },
                    {
                        field: 'unit',
                        title: '单位'
                    },
                    {
                        field: 'price',
                        title: '商品单价'
                    },
                    {
                        field: 'nums',
                        title: '数量'
                    },
                    {
                        field: 'subtotal',
                        title: '小计'
                    },
                    {
                        field: 'typeid',
                        title: __('Typeid')
                    },
                    {
                        field: 'operate',
                        title: __('Operate')
                    },
                ]
            })
            var ProData = Config.Product.OrderProductList
            console.log(ProData);
            // return  false;
            // 添加商品的数据
            var list = []

            // 商品id
            var arr = []

            // 存放商品的数量单价数据
            var ProductList = []

            // 存放商品的数量单价id
            var ProidList = []

            // 定义删除时，把已在数据库的商品追加到这里
            var DelIdList = []
            if (ProData.length > 0) {
                let tr = ''

                let index = 0

                let TotalCount = 0

                let NumCount = 0

                for (let item of ProData) {
                    console.log(item);
                    // return false
                    tr += `<tr data-index="${index++}">`
                    tr += `<td>${item.product.id}</td>`
                    tr += `<td>${item.product.name}</td>`
                    tr += `<td>${item.product.unit.name}</td>`
                    tr += `<td><input name="row[price]" class="price" type="number" min="0" value="${item.price}" /></td>`
                    tr += `<td><input name="row[nums]" class="nums" type="number" min="0" value="${item.pronum}" /></td>`
                    tr += `<td class="subtotal">${item.total}</td>`
                    tr += `<td>${item.product.type.name}</td>`
                    tr += `<td>
                                <button class="btn btn-primary btn-xs ProAdd">添加</button>
                                <button class="btn btn-danger btn-xs ProDel">删除</button>
                            </td>`
                    tr += `</tr>`

                    tr += `<tr id="count">`

                    list.push(item.product)

                    arr.push(item.product.id)

                    ProductList.push({
                        id: item.id,
                        proid: item.product.id,
                        price: item.price,
                        nums: item.pronum,
                        total: item.total // 这个是单价*数量
                    })

                    ProidList.push(item.product.id)

                    TotalCount += item.total ? parseFloat(item.total) : 0

                    NumCount += item.pronum ? parseInt(item.pronum) : 0
                    $('#total').val(TotalCount)
                    $('#nums').val(NumCount)

                }

                tr += `<td>合计</td>`
                tr += `<td></td>`
                tr += `<td></td>`
                tr += `<td></td>`
                tr += `<td class="product-nums">${NumCount}</td>`
                tr += `<td class="total">${TotalCount.toFixed(2)}</td>`
                tr += `<td></td>`
                tr += `<td></td>`
                tr += `</tr>`

                $('#products').val(JSON.stringify(ProductList))

                $('#product').css({ 'display': 'none' })

                $('#table tbody').html(tr)
            }
            // 从表格删除商品
            $('#table').on('click', '.ProDel', function () {

                if (list.length == 1) {

                    Backend.api.msg('这是最后一件商品')
                    return false

                }

                let index = $(this).parents('tr').data('index')

                $(this).parents('tr').remove()

                list.splice(index, 1)

                // 追加数组
                DelIdList.push(ProductList[index].id)

                arr.splice(index, 1)

                ProductList.splice(index, 1)

                ProidList.splice(index, 1)

                $('#products').val(JSON.stringify(ProductList))

                var subtotal = $('.subtotal')

                var total = 0

                for (let item of subtotal) {
                    total += item.innerText ? parseFloat(item.innerText) : 0
                }

                $('#total').val(total)
                   

                $('.total').text(total.toFixed(2))

                // 计算每件商品数量
                var nums = $('.nums')

                var ProductsNums = 0

                for (let item of nums) {
                    ProductsNums += item.value ? parseInt(item.value) : 0
                }
                $('#nums').val(ProductsNums)


                $('.product-nums').text(ProductsNums)

                $('#delproid').val(JSON.stringify(DelIdList))

                return false
            })
            // 从表格添加商品
            $('#table').on('click', '.ProAdd', function () {

                let index = $(this).parents('tr').data('index')

                let parent = $(this).parents('tr')
                Backend.api.open('depot/storage/product', '商品', {
                    area: ['80%', '80%'],
                    callback: function (data) {
                        if (arr.includes(data.id)) {
                            Backend.api.msg('添加商品已存在')
                            return false
                        }

                        let tr = `
                            <tr data-index="${index + 1}">
                                <td>${data.id}</td>
                                <td>${data.name}</td>
                                <td>${data.unit.name}</td>
                                <td><input name="row[price]" class="price" type="number" min="1" value="${data.price}" /></td>
                                <td><input name="row[nums]" class="nums" type="number" min="1" /></td>
                                <td class="subtotal"></td>
                                <td>${data.type.name}</td>
                                <td>
                                    <button class="btn btn-primary btn-xs ProAdd">添加</button>
                                    <button class="btn btn-danger btn-xs ProDel">删除</button>
                                </td>
                            </tr>
                        `;

                        parent.after(tr)

                        list.push(data)

                        arr.push(data.id)
                    }
                })

                return false
            })
            // 判断单价是是否为空
            $('#table').on('blur','.price',function(){

                $(this).next().remove()

                if(!$(this).val())
                {
                    $(this).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`)
                    return false
                }

                if($(this).val() == 0)
                {
                    $(this).after(`<span style="color:red;margin-left:5px;">单价不能少1.00</span>`)
                    return false
                }

                // 获取单价
                var price = $(this).val() ? parseFloat($(this).val()) : 0

                // 获取相邻的数量
                var num = $(this).parent('td').next().find('input').val() ? parseInt($(this).parent('td').next().find('input').val()) : 0

                // 获取当前的商品id
                var proid = $(this).parent().prev().prev().prev().text()

                var Price = price * num

                if(Price >= 0)
                {
                    $(this).parent('td').next().next().text(Price.toFixed(2))

                    // 计算每件商品数量
                    var nums = $('.nums')

                    var ProductsNums = 0

                    for(let item of nums)
                    {
                        ProductsNums += item.value ? parseInt(item.value) : 0
                    }

                    $('.product-nums').text(ProductsNums)

                    var subtotal = $('.subtotal')

                    var total = 0

                    for(let item of subtotal)
                    {
                        total += item.innerText ? parseFloat(item.innerText) : 0
                    }

                    $('.total').text(total.toFixed(2))

                    $('#total').val(total)
                    
                    if(ProidList.includes(parseInt(proid)))
                    {
                        for(let item of ProductList)
                        {
                            if(proid == item.proid)
                            {
                                item.price = price
                                item.nums = num
                                item.total = Price
                            }
                        }
                        
                    }else{
                        ProductList.push({
                            proid:proid,
                            price:price,
                            nums:num,
                            total:Price // 这个是单价*数量
                        })

                        ProidList.push(parseInt(proid))
                    }

                    $('#products').val(JSON.stringify(ProductList))
                }
                
            })

            // 数量
            $('#table').on('blur','.nums',function(){

                $(this).next().remove()

                if(!$(this).val())
                {
                    $(this).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`)

                    return false
                }
                
                if($(this).val() == 0)
                {
                    $(this).after(`<span style="color:red;margin-left:5px;">数量不能少1</span>`)
                    return false
                }

                // 获取相邻的单价
                var price = $(this).parent('td').prev().find('input').val() ? parseFloat($(this).parent('td').prev().find('input').val()) : 0

                // 获取当前的商品id
                var proid = $(this).parent().prev().prev().prev().prev().text()

                // 获取当前的数量
                var num = $(this).val() ? parseInt($(this).val()) : 0

                var Price = price * num

                if(Price >= 0)
                {
                    $(this).parent('td').next().text(Price.toFixed(2))

                    // 计算每件商品数量
                    var nums = $('.nums')

                    var ProductsNums = 0

                    for(let item of nums)
                    {
                        ProductsNums += item.value ? parseInt(item.value) : 0
                    }

                    
                    $('.product-nums').text(ProductsNums)

                    $('#nums').val(ProductsNums)

                    var subtotal = $('.subtotal')

                    var total = 0

                    for(let item of subtotal)
                    {
                        total += item.innerText ? parseFloat(item.innerText) : 0
                    }

                    $('.total').text(total.toFixed(2))

                    $('#total').val(total)

                    if(ProidList.includes(parseInt(proid)))
                    {
                        for(let item of ProductList)
                        {
                            if(proid == item.proid)
                            {
                                item.price = price
                                item.nums = num
                                item.total = Price
                            }
                        }
                        
                    }else{
                        ProductList.push({
                            proid:proid,
                            price:price,
                            nums:num,
                            total:Price // 这个是单价*数量
                        })

                        ProidList.push(parseInt(proid))
                    }

                    $('#products').val(JSON.stringify(ProductList))
                }
            })
            Controller.api.bindevent();
        },
        del: function () {
            Controller.api.bindevent();
        },
        address:function(){
            var busid=location.href.split("=")[1].split('&')[0]
            console.log(busid);
            Table.api.init({
            });
            // console.log(business.id);
            var addressTable = $("#table");
            // 初始化表格
            addressTable.bootstrapTable({
                url: 'order/order/address?busid='+busid,
                pk: 'address.id',
                sortName: 'address.id',
                search: false,
                // 关闭导出
                showExport: false,
                // 关闭通用搜索
                commonSearch: false,
                // 关闭显示的列
                showColumns: false,
                // 关闭切换显示
                showToggle: false,
                columns: [
                    [
                        // {checkbox: true},
                        { field: 'id', title: __('Id') ,sortName:false},
                        { field: 'business.nickname_text', title: __('busid'), operate: 'LIKE' },
                        { field: 'consignee', title: __('consignee'), operate: 'LIKE' },
                        { field: 'mobile', title: __('mobile'), operate: 'LIKE' },
                        { field: 'address_text', title: __('businessaddrid'), operate: 'LIKE' },
                        { field: 'address', title: __('address'), operate: 'LIKE' },
                        { field: 'status_text', title: __('addressStatus'), operate: 'LIKE' },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: addressTable,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'chapter', text: '选择',
                                    title: '选择',
                                    classname: 'btn btn-primary btn-xs address',
                                },
                            ]
                        }
                    ]
                ]
            });
            // 点击选择
            $('#table').on('click', '.address', function () {
                let index = $(this).parents('tr').data('index')
                let data = Table.api.getrowdata(addressTable, index);
                // console.log(data);
                Backend.api.close(data)
            })
            // 为表格绑定事件
            Table.api.bindevent(addressTable);
        },
        recycle: function ()
        {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    recyclebin_url: 'order/order/recycle',
                    del_url: 'order/order/destroy',
                    restore_url: 'order/order/restore',
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.recyclebin_url,
                pk: 'id',
                sortName: 'order.id',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), sortable: true },
                        { field: 'code', title: __('code'), operate: 'LIKE' },
                        {
                            field: 'business.nickname_text', title: __('busid'), operate: 'LIKE',
                            
                        },
                        // { field: 'businessaddrid', title: __('businessaddrid'), operate: 'LIKE'},
                        { field: 'amount', title: __('amount'), operate: 'LIKE' },
                        // { field: 'status', title: __('status'), searchable: false },
                        { field: 'status', title: __('Status'), searchList: { "0": __('未支付'), "1": __('已支付'), "2": __('已发货'), "3": __('已收货'), "-1": __('退货') }, formatter: Table.api.formatter.status },
                        // { field: 'status_text', title: __('status'), searchList: { "0": __('未支付'), "1": __('已支付'), "2": __('已发货'), "3": __('已收货'), "-1": __('退货') }, formatter: Table.api.formatter.status },
                        { field: 'createtime', title: __('createtime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange'},
                        { field: 'checkmanid', title: __('checkmanid'), searchable: false },
                        { field: 'admin.username', title: __('shipmanid'), searchable: false },
                        {
                            field: 'operate',
                            title: __('Operate'), 
                            table: table, 
                            events: Table.api.events.operate, 
                            formatter: Table.api.formatter.operate,
                            //要在操作这一栏增添自定义的按钮
                            buttons:[
                                {
                                    name:'restore',
                                    title:'数据恢复',
                                    icon:'fa fa-reply',
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    url:$.fn.bootstrapTable.defaults.extend.restore_url,
                                    confirm: '是否还原订单',
                                    extend:"data-toggle='tooltip'",
                                    success:function(data)
                                    {
                                        //ajax成功会刷新一下table数据列表
                                        table.bootstrapTable('refresh');
                                    }
                                }
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            //给表格的按钮绑定点击事件
            $(document).on('click', '.btn-restore', function(){
                // 弹出确认对话框
                Layer.confirm(__('是否确认还原数据'), { icon: 3, title: __('Warning'), shadeClose: true }, function(index){
                    //获取当前选中id
                    var ids = Table.api.selectedids(table)

                    //发送ajax请求
                    Backend.api.ajax(
                        //请求地址
                        {url:$.fn.bootstrapTable.defaults.extend.restore_url + `?ids=${ids}`},
                        //回调函数
                        function()
                        {
                            // 关闭窗口
                            Layer.close(index)

                            //刷新数据表格
                            table.bootstrapTable('refresh')
                        }
                    )
                })
            })
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});